package com.atguigu.bigdata.gmall.realtime.util;

import com.atguigu.bigdata.gmall.realtime.common.Constant;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @Author lzc
 * @Date 2022/10/19 09:26
 */
public class RedisUtil {
    
    private static final JedisPool pool;
    
    static {
        // 静态代码块
        GenericObjectPoolConfig conf = new JedisPoolConfig();
        conf.setMaxTotal(100);
        conf.setMaxIdle(10);
        conf.setMinIdle(2);
        conf.setTestOnCreate(true);
        conf.setTestOnBorrow(true);
        conf.setTestOnReturn(true);
        conf.setMaxWaitMillis(10000);
        pool = new JedisPool(conf, Constant.REDIS_HOST, Constant.REDIS_PORT);
        
    }
    public  static Jedis getRedisClient(){
        Jedis jedis = pool.getResource();
        jedis.select(4);
        return jedis;
    }
    
    public static void close(Jedis jedis) {
        if (jedis != null) {
            // 客户端是从连接池获取, 这里的 close 不是关闭, 而是归还
            // 如果客户端是 new Jedis(), 就是真正的关闭了.
            jedis.close();
            
        }
    }
}
